package com.sto.stoapp.thread;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Looper;

import com.sto.stoapp.file.SmzFile;

public class SmzApkDownloadThread extends BaseThread {
	private Context context;
	BootReceiver installApk;
	SmzFile smzfile;
	boolean isinstallApk;
	IntentFilter infter;
	
	Handler handler = new Handler(Looper.getMainLooper());
	
	public SmzApkDownloadThread(Context context) {
		super(context);
		this.context = context;
		smzfile = new SmzFile(context);
		installApk = new BootReceiver();
		infter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
		infter.addDataScheme("package");
		context.registerReceiver(installApk, infter);
		
		showDialogByMessage("正在下载插件，请稍后");
	}

	@Override
	public void run() {
		super.run();
		int num = 0;
//		if(smzfile.downfile("site_zj.txt")){
//			// 下载成功
//			
//		}
		// 下载成功
		if(smzfile.downSmzZjFile()){
			// 监听安装包师傅完成
			handler.post(new Runnable() {
				
				@Override
				public void run() {
				//	正在安装插件，请稍后
					setProgressMessage("正在安装，请稍后");	
				}
			});
		
			while (!isinstallApk) {
				// 最多50秒安装时间
				if(num > 100){
					break;
				}
				try {
					sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				num++;
			}
		}
		context.unregisterReceiver(installApk);
		cancelDialog();
	}
	
	class BootReceiver extends BroadcastReceiver {
	      
		@Override
		public void onReceive(Context context, Intent intent) {
			//接收安装广播 
	        if (intent.getAction().equals("android.intent.action.PACKAGE_ADDED")) {   
	            String packageName = intent.getDataString();
	            if(packageName.equals("package:kaicom.com.security")){
	            	isinstallApk = true;
	            }
	        }
			
		}
	} 

}
